home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Environments / PowerLisp 2.01 / Supplemental Documentation / Documentation / Chapter 08. Macros < prev    next >
Text File  |  1995-03-27  |  50KB  |  1,103 lines

  1. Common Lisp the Language, 2nd Edition
  2. -------------------------------------------------------------------------------
  3.  
  4. 8. Macros
  5.  
  6. The Common Lisp macro facility allows the user to define arbitrary functions
  7. that convert certain Lisp forms into different forms before evaluating or
  8. compiling them. This is done at the expression level, not at the
  9. character-string level as in most other languages. Macros are important in the
  10. writing of good code: they make it possible to write code that is clear and
  11. elegant at the user level but that is converted to a more complex or more
  12. efficient internal form for execution.
  13.  
  14. When eval is given a list whose car is a symbol, it looks for local definitions
  15. of that symbol (by flet, labels, and macrolet); if that fails, it looks for a
  16. global definition. If the definition is a macro definition, then the original
  17. list is said to be a macro call. Associated with the definition will be a
  18. function of two arguments, called the expansion function. This function is
  19. called with the entire macro call as its first argument (the second argument is
  20. a lexical environment); it must return some new Lisp form, called the expansion
  21. of the macro call. (Actually, a more general mechanism is involved; see
  22. macroexpand.) This expansion is then evaluated in place of the original form.
  23.  
  24. When a function is being compiled, any macros it contains are expanded at
  25. compilation time. This means that a macro definition must be seen by the
  26. compiler before the first use of the macro.
  27.  
  28. More generally, an implementation of Common Lisp has great latitude in deciding
  29. exactly when to expand macro calls within a program. For example, it is
  30. acceptable for the defun special form to expand all macro calls within its body
  31. at the time the defun form is executed and record the fully expanded body as
  32. the body of the function being defined. (An implementation might even choose
  33. always to compile functions defined by defun, even when operating in an
  34. ``interpretive'' mode.)
  35.  
  36. Macros should be written so as to depend as little as possible on the execution
  37. environment to produce a correct expansion. To ensure consistent behavior, it
  38. is best to ensure that all macro definitions are available, whether to the
  39. interpreter or compiler, before any code containing calls to those macros is
  40. introduced.
  41.  
  42. In Common Lisp, macros are not functions. In particular, macros cannot be used
  43. as functional arguments to such functions as apply, funcall, or map; in such
  44. situations, the list representing the ``original macro call'' does not exist,
  45. and cannot exist, because in some sense the arguments have already been
  46. evaluated.
  47.  
  48. -------------------------------------------------------------------------------
  49.  
  50.    *  Macro Definition
  51.    *  Macro Expansion
  52.    *  Destructuring
  53.    *  Compiler Macros
  54.    *  Environments
  55.  
  56. -------------------------------------------------------------------------------
  57.  
  58. 8.1. Macro Definition
  59.  
  60. The function macro-function determines whether a given symbol is the name of a
  61. macro. The defmacro construct provides a convenient way to define new macros.
  62.  
  63. [old_change_begin]
  64.  
  65. [Function]
  66. macro-function symbol
  67.  
  68. The argument must be a symbol. If the symbol has a global function definition
  69. that is a macro definition, then the expansion function (a function of two
  70. arguments, the macro-call form and an environment) is returned. If the symbol
  71. has no global function definition, or has a definition as an ordinary function
  72. or as a special form but not as a macro, then nil is returned. The function
  73. macroexpand is the best way to invoke the expansion function.
  74.  
  75. It is possible for both macro-function and special-form-p to be true of a
  76. symbol. This is possible because an implementation is permitted to implement
  77. any macro also as a special form for speed. On the other hand, the macro
  78. definition must be available for use by programs that understand only the
  79. standard special forms listed in table 5-1.
  80.  
  81. macro-function cannot be used to determine whether a symbol names a locally
  82. defined macro established by macrolet; macro-function can examine only global
  83. definitions.
  84.  
  85. setf may be used with macro-function to install a macro as a symbol's global
  86. function definition:
  87.  
  88. (setf (macro-function symbol) fn)
  89.  
  90. The value installed must be a function that accepts two arguments, an entire
  91. macro call and an environment, and computes the expansion for that call.
  92. Performing this operation causes the symbol to have only that macro definition
  93. as its global function definition; any previous definition, whether as a macro
  94. or as a function, is lost. It is an error to attempt to redefine the name of a
  95. special form.
  96. [old_change_end]
  97.  
  98. [change_begin]
  99. X3J13 voted in March 1988 (MACRO-FUNCTION-ENVIRONMENT)   to add an optional
  100. environment argument to macro-function.
  101.  
  102. [Function]
  103. macro-function symbol &optional env
  104.  
  105. The first argument must be a symbol. If the symbol has a function definition
  106. that is a macro definition, whether a local one established in the environment
  107. env by macrolet or a global one established as if by defmacro, then the
  108. expansion function (a function of two arguments, the macro-call form and an
  109. environment) is returned. If the symbol has no function definition, or has a
  110. definition as an ordinary function or as a special form but not as a macro,
  111. then nil is returned. The function macroexpand or macroexpand-1 is the best way
  112. to invoke the expansion function.
  113.  
  114. It is possible for both macro-function and special-form-p to be true of a
  115. symbol. This is possible because an implementation is permitted to implement
  116. any macro also as a special form for speed. On the other hand, the macro
  117. definition must be available for use by programs that understand only the
  118. standard special forms listed in table 5-1.
  119.  
  120. setf may be used with macro-function to install a macro as a symbol's global
  121. function definition:
  122.  
  123. (setf (macro-function symbol) fn)
  124.  
  125. The value installed must be a function that accepts two arguments, an entire
  126. macro call and an environment, and computes the expansion for that call.
  127. Performing this operation causes the symbol to have only that macro definition
  128. as its global function definition; any previous definition, whether as a macro
  129. or as a function, is lost. One cannot use setf to establish a local macro
  130. definition; it is an error to supply a second argument to macro-function when
  131. using it with setf. It is an error to attempt to redefine the name of a special
  132. form.
  133.  
  134. See also compiler-macro-function.
  135. [change_end]
  136.  
  137. [Macro]
  138.  
  139. defmacro name lambda-list [[ {declaration}* | doc-string ]] {form}*
  140.  
  141. defmacro is a macro-defining macro that arranges to decompose the macro-call
  142. form in an elegant and useful way. defmacro has essentially the same syntax as
  143. defun: name is the symbol whose macro definition we are creating, lambda-list
  144. is similar in form to a lambda-list, and the forms constitute the body of the
  145. expander function. The defmacro construct arranges to install this expander
  146. function, as the global macro definition of name.
  147.  
  148. [old_change_begin]
  149. The expander function is effectively defined in the global environment;
  150. lexically scoped entities established outside the defmacro form that would
  151. ordinarily be lexically apparent are not visible within the body of the
  152. expansion function.
  153. [old_change_end]
  154.  
  155. [change_begin]
  156. X3J13 voted in March 1989 (DEFINING-MACROS-NON-TOP-LEVEL)   to clarify that,
  157. while defining forms normally appear at top level, it is meaningful to place
  158. them in non-top-level contexts. Furthermore, defmacro should define the
  159. expander function within the enclosing lexical environment, not within the
  160. global environment.
  161.  
  162. X3J13 voted in March 1988 (FLET-IMPLICIT-BLOCK)   to specify that the body of
  163. the expander function defined by defmacro is implicitly enclosed in a block
  164. construct whose name is the same as the name of the defined macro. Therefore
  165. return-from may be used to exit from the function.
  166. [change_end]
  167.  
  168. The name is returned as the value of the defmacro form.
  169.  
  170. If we view the macro call as a list containing a function name and some
  171. argument forms, in effect the expander function and the list of (unevaluated)
  172. argument forms is given to apply. The parameter specifiers are processed as for
  173. any lambda-expression, using the macro-call argument forms as the arguments.
  174. Then the body forms are evaluated as an implicit progn, and the value of the
  175. last form is returned as the expansion of the macro call.
  176.  
  177. If the optional documentation string doc-string is present (if not followed by
  178. a declaration, it may be present only if at least one form is also specified,
  179. as it is otherwise taken to be a form), then it is attached to the name as a
  180. documentation string of type function; see documentation.
  181.  
  182. [old_change_begin]
  183. Like the lambda-list in a defun, a defmacro lambda-list may contain the
  184. lambda-list keywords &optional, &rest, &key, &allow-other-keys, and &aux. For
  185. &optional and &key parameters, initialization forms and supplied-p parameters
  186. may be specified, just as for defun. Three additional markers are allowed in
  187. defmacro variable lists only.
  188. [old_change_end]
  189.  
  190. [change_begin]
  191. These three markers are now allowed in other constructs as well.
  192. [change_end]
  193.  
  194. &body
  195.      This is identical in function to &rest, but it informs certain
  196.      output-formatting and editing functions that the remainder of the form is
  197.      treated as a body and should be indented accordingly. (Only one of &body
  198.      or &rest may be used.)
  199.  
  200. &whole
  201.      This is followed by a single variable that is bound to the entire
  202.      macro-call form; this is the value that the macro definition function
  203.      receives as its single argument. &whole and the following variable should
  204.      appear first in the lambda-list, before any other parameter or lambda-list
  205.      keyword.
  206.  
  207. &environment
  208.      This is followed by a single variable that is bound to an environment
  209.      representing the lexical environment in which the macro call is to be
  210.      interpreted. This environment may not be the complete lexical environment;
  211.      it should be used only with the function macroexpand for the sake of any
  212.      local macro definitions that the macrolet construct may have established
  213.      within that lexical environment. This is useful primarily in the rare
  214.      cases where a macro definition must explicitly expand any macros in a
  215.      subform of the macro call before computing its own expansion.
  216.  
  217. See lambda-list-keywords.
  218.  
  219. [change_begin]
  220. Notice of correction. In the first edition, the symbol &environment at the left
  221. margin above was inadvertently omitted.
  222.  
  223. X3J13 voted in March 1989 (MACRO-ENVIRONMENT-EXTENT)   to specify that macro
  224. environment objects received with the &environment argument of a macro function
  225. have only dynamic extent. The consequences are undefined if such objects are
  226. referred to outside the dynamic extent of that particular invocation of the
  227. macro function. This allows implementations to use somewhat more efficient
  228. techniques for representing environment objects.
  229.  
  230. X3J13 voted in March 1989 (DEFMACRO-LAMBDA-LIST)   to clarify the permitted
  231. uses of &body, &whole, and &environment:
  232.  
  233.    *  &body may appear at any level of a defmacro lambda-list.
  234.  
  235.    *  &whole may appear at any level of a defmacro lambda-list. At inner levels
  236.      a &whole variable is bound to that part of the argument that matches the
  237.      sub-lambda-list in which &whole appears. No matter where &whole is used,
  238.      other parameters or lambda-list keywords may follow it.
  239.  
  240.    *  &environment may occur only at the outermost level of a defmacro
  241.      lambda-list, and it may occur at most once, but it may occur anywhere
  242.      within that lambda-list, even before an occurrence of &whole.
  243.  
  244. [change_end]
  245.  
  246. defmacro, unlike any other Common Lisp construct that has a lambda-list as part
  247. of its syntax, provides an additional facility known as destructuring.
  248.  
  249. [change_begin]
  250. See destructuring-bind, which provides the destructuring facility separately.
  251. [change_end]
  252.  
  253. Anywhere in the lambda-list where a parameter name may appear, and where
  254. ordinary lambda-list syntax (as described in section 5.2.2) does not otherwise
  255. allow a list, a lambda-list may appear in place of the parameter name. When
  256. this is done, then the argument form that would match the parameter is treated
  257. as a (possibly dotted) list, to be used as an argument forms list for
  258. satisfying the parameters in the embedded lambda-list. As an example, one could
  259. write the macro definition for dolist in this manner:
  260.  
  261. (defmacro dolist ((var listform &optional resultform)
  262.                   &rest body)
  263.   ...)
  264.  
  265. More examples of embedded lambda-lists in defmacro are shown below.
  266.  
  267. Another destructuring rule is that defmacro allows any lambda-list (whether
  268. top-level or embedded) to be dotted, ending in a parameter name. This situation
  269. is treated exactly as if the parameter name that ends the list had appeared
  270. preceded by &rest. For example, the definition skeleton for dolist shown above
  271. could instead have been written
  272.  
  273. (defmacro dolist ((var listform &optional resultform)
  274.                   . body)
  275.   ...)
  276.  
  277. If the compiler encounters a defmacro, the new macro is added to the
  278. compilation environment, and a compiled form of the expansion function is also
  279. added to the output file so that the new macro will be operative at run time.
  280. If this is not the desired effect, the defmacro form can be wrapped in an
  281. eval-when construct.
  282.  
  283. It is permissible to use defmacro to redefine a macro (for example, to install
  284. a corrected version of an incorrect definition), or to redefine a function as a
  285. macro. It is an error to attempt to redefine the name of a special form (see
  286. table 5-1) as a macro. See macrolet, which establishes macro definitions over a
  287. restricted lexical scope.
  288.  
  289. [change_begin]
  290. See also define-compiler-macro.
  291. [change_end]
  292.  
  293. Suppose, for the sake of example, that it were desirable to implement a
  294. conditional construct analogous to the Fortran arithmetic IF statement. (This
  295. of course requires a certain stretching of the imagination and suspension of
  296. disbelief.) The construct should accept four forms: a test-value, a neg-form, a
  297. zero-form, and a pos-form. One of the last three forms is chosen to be executed
  298. according to whether the value of the test-form is positive, negative, or zero.
  299. Using defmacro, a definition for such a construct might look like this:
  300.  
  301. (defmacro arithmetic-if (test neg-form zero-form pos-form)
  302.   (let ((var (gensym)))
  303.     `(let ((,var ,test))
  304.        (cond ((< ,var 0) ,neg-form)
  305.              ((= ,var 0) ,zero-form)
  306.              (t ,pos-form)))))
  307.  
  308. Note the use of the backquote facility in this definition (see section 22.1.3).
  309. Also note the use of gensym to generate a new variable name. This is necessary
  310. to avoid conflict with any variables that might be referred to in neg-form,
  311. zero-form, or pos-form.
  312.  
  313. If the form is executed by the interpreter, it will cause the function
  314. definition of the symbol arithmetic-if to be a macro associated with which is a
  315. two-argument expansion function roughly equivalent to
  316.  
  317. (lambda (calling-form environment)
  318.   (declare (ignore environment))
  319.   (let ((var (gensym)))
  320.     (list 'let
  321.           (list (list 'var (cadr calling-form)))
  322.           (list 'cond
  323.                 (list (list '< var '0) (caddr calling-form))
  324.                 (list (list '= var '0) (cadddr calling-form))
  325.                 (list 't (fifth calling-form))))))
  326.  
  327. The lambda-expression is produced by the defmacro declaration. The calls to
  328. list are the (hypothetical) result of the backquote (`) macro character and its
  329. associated commas. The precise macro expansion function may depend on the
  330. implementation, for example providing some degree of explicit error checking on
  331. the number of argument forms in the macro call.
  332.  
  333. Now, if eval encounters
  334.  
  335. (arithmetic-if (- x 4.0)
  336.                (- x)
  337.                (error "Strange zero")
  338.                x)
  339.  
  340. this will be expanded into something like
  341.  
  342. (let ((g407 (- x 4.0)))
  343.   (cond ((< g407 0) (- x))
  344.         ((= g407 0) (error "Strange zero"))
  345.         (t x)))
  346.  
  347. and eval tries again on this new form. (It should be clear now that the
  348. backquote facility is very useful in writing macros, since the form to be
  349. returned is normally a complex list structure, typically consisting of a mostly
  350. constant template with a few evaluated forms here and there. The backquote
  351. template provides a ``picture'' of the resulting code, with places to be filled
  352. in indicated by preceding commas.)
  353.  
  354. To expand on this example, stretching credibility to its limit, we might allow
  355. the pos-form and zero-form to be omitted, allowing their values to default to
  356. nil, in much the same way that the else form of a Common Lisp if construct may
  357. be omitted:
  358.  
  359. (defmacro arithmetic-if (test neg-form
  360.                          &optional zero-form pos-form)
  361.   (let ((var (gensym)))
  362.     `(let ((,var ,test))
  363.        (cond ((< ,var 0) ,neg-form)
  364.              ((= ,var 0) ,zero-form)
  365.              (t ,pos-form)))))
  366.  
  367. Then one could write
  368.  
  369. (arithmetic-if (- x 4.0) (print x))
  370.  
  371. which would be expanded into something like
  372.  
  373. (let ((g408 (- x 4.0)))
  374.   (cond ((< g408 0) (print x))
  375.         ((= g408 0) nil)
  376.         (t nil)))
  377.  
  378. The resulting code is correct but rather silly-looking. One might rewrite the
  379. macro definition to produce better code when pos-form and possibly zero-form
  380. are omitted, or one might simply rely on the Common Lisp implementation to
  381. provide a compiler smart enough to improve the code itself.
  382.  
  383. Destructuring is a very powerful facility that allows the defmacro lambda-list
  384. to express the structure of a complicated macro-call syntax. If no lambda-list
  385. keywords appear, then the defmacro lambda-list is simply a list, nested to some
  386. extent, containing parameter names at the leaves. The macro-call form must have
  387. the same list structure. For example, consider this macro definition:
  388.  
  389. (defmacro halibut ((mouth eye1 eye2)
  390.                    ((fin1 length1) (fin2 length2))
  391.                    tail)
  392.   ...)
  393.  
  394. Now consider this macro call:
  395.  
  396. (halibut (m (car eyes) (cdr eyes))
  397.          ((f1 (count-scales f1)) (f2 (count-scales f2)))
  398.          my-favorite-tail)
  399.  
  400. This would cause the expansion function to receive the following values for its
  401. parameters:
  402.  
  403. Parameter       Value
  404. ---------------------------------
  405. mouth           m
  406. eye1            (car eyes)
  407. eye2            (cdr eyes)
  408. fin1            f1
  409. length1         (count-scales f1)
  410. fin2            f2
  411. length2         (count-scales f2)
  412. tail            my-favorite-tail
  413. ---------------------------------
  414.  
  415. The following macro call would be in error because there would be no argument
  416. form to match the parameter length1:
  417.  
  418. (halibut (m (car eyes) (cdr eyes))
  419.          ((f1) (f2 (count-scales f2)))
  420.          my-favorite-tail)
  421.  
  422. The following macro call would be in error because a symbol appears in the call
  423. where the structure of the lambda-list requires a list.
  424.  
  425. (halibut my-favorite-head
  426.          ((f1 (count-scales f1)) (f2 (count-scales f2)))
  427.          my-favorite-tail)
  428.  
  429. The fact that the value of the variable my-favorite-head might happen to be a
  430. list is irrelevant here. It is the macro call itself whose structure must match
  431. that of the defmacro lambda-list.
  432.  
  433. The use of lambda-list keywords adds even greater flexibility. For example,
  434. suppose it is convenient within the expansion function for halibut to be able
  435. to refer to the list whose components are called mouth, eye1, and eye2 as head.
  436. One may write this:
  437.  
  438. (defmacro halibut ((&whole head mouth eye1 eye2)
  439.                    ((fin1 length1) (fin2 length2))
  440.                    tail)
  441.  
  442. Now consider the same valid macro call as before:
  443.  
  444. (halibut (m (car eyes) (cdr eyes))
  445.          ((f1 (count-scales f1)) (f2 (count-scales f2)))
  446.          my-favorite-tail)
  447.  
  448. This would cause the expansion function to receive the same values for its
  449. parameters and also a value for the parameter head:
  450.  
  451. Parameter       Value
  452. ------------------------------------------
  453. head            (m (car eyes) (cdr eyes))
  454. ------------------------------------------
  455.  
  456. The stipulation that an embedded lambda-list is permitted only where ordinary
  457. lambda-list syntax would permit a parameter name but not a list is made to
  458. prevent ambiguity. For example, one may not write
  459.  
  460. (defmacro loser (x &optional (a b &rest c) &rest z)
  461.   ...)
  462.  
  463. because ordinary lambda-list syntax does permit a list following &optional; the
  464. list (a b &rest c) would be interpreted as describing an optional parameter
  465. named a whose default value is that of the form b, with a supplied-p parameter
  466. named &rest (not legal), and an extraneous symbol c in the list (also not
  467. legal). An almost correct way to express this is
  468.  
  469. (defmacro loser (x &optional ((a b &rest c)) &rest z)
  470.   ...)
  471.  
  472. The extra set of parentheses removes the ambiguity. However, the definition is
  473. now incorrect because a macro call such as (loser (car pool)) would not provide
  474. any argument form for the lambda-list (a b &rest c), and so the default value
  475. against which to match the lambda-list would be nil because no explicit default
  476. value was specified. This is in error because nil is an empty list; it does not
  477. have forms to satisfy the parameters a and b. The fully correct definition
  478. would be either
  479.  
  480. (defmacro loser (x &optional ((a b &rest c) '(nil nil)) &rest z)
  481.   ...)
  482.  
  483. or
  484.  
  485. (defmacro loser (x &optional ((&optional a b &rest c)) &rest z)
  486.   ...)
  487.  
  488. These differ slightly: the first requires that if the macro call specifies a
  489. explicitly then it must also specify b explicitly, whereas the second does not
  490. have this requirement. For example,
  491.  
  492. (loser (car pool) ((+ x 1)))
  493.  
  494. would be a valid call for the second definition but not for the first.
  495.  
  496. -------------------------------------------------------------------------------
  497.  
  498. 8.2. Macro Expansion
  499.  
  500. The macroexpand function is the conventional means for expanding a macro call.
  501. A hook is provided for a user function to gain control during the expansion
  502. process.
  503.  
  504. [Function]
  505. macroexpand form &optional env
  506. macroexpand-1 form &optional env
  507.  
  508. If form is a macro call, then macroexpand-1 will expand the macro call once and
  509. return two values: the expansion and t. If form is not a macro call, then the
  510. two values form and nil are returned.
  511.  
  512. A form is considered to be a macro call only if it is a cons whose car is a
  513. symbol that names a macro. The environment env is similar to that used within
  514. the evaluator (see evalhook); it defaults to a null environment. Any local
  515. macro definitions established within env by macrolet will be considered. If
  516. only form is given as an argument, then the environment is effectively null,
  517. and only global macro definitions (as established by defmacro) will be
  518. considered.
  519.  
  520. Macro expansion is carried out as follows. Once macroexpand-1 has determined
  521. that a symbol names a macro, it obtains the expansion function for that macro.
  522. The value of the variable *macroexpand-hook* is then called as a function of
  523. three arguments: the expansion function, the form, and the environment env. The
  524. value returned from this call is taken to be the expansion of the macro call.
  525. The initial value of *macroexpand-hook* is funcall, and the net effect is to
  526. invoke the expansion function, giving it form and env as its two arguments.
  527.  
  528. [change_begin]
  529. X3J13 voted in June 1988 (FUNCTION-TYPE)   to specify that the value of
  530. *macroexpand-hook* is first coerced to a function before being called as the
  531. expansion interface hook. Therefore its value may be a symbol, a
  532. lambda-expression, or any object of type function.
  533.  
  534. X3J13 voted in March 1989 (MACRO-ENVIRONMENT-EXTENT)   to specify that macro
  535. environment objects received by a *macroexpand-hook* function have only dynamic
  536. extent. The consequences are undefined if such objects are referred to outside
  537. the dynamic extent of that particular invocation of the hook function. This
  538. allows implementations to use somewhat more efficient techniques for
  539. representing environment objects.
  540. [change_end]
  541.  
  542. [old_change_begin]
  543. (The purpose of *macroexpand-hook* is to facilitate various techniques for
  544. improving interpretation speed by caching macro expansions.)
  545. [old_change_end]
  546.  
  547. [change_begin]
  548. X3J13 voted in June 1989 (MACRO-CACHING)   to clarify that, while
  549. *macroexpand-hook* may be useful for debugging purposes, despite the original
  550. design intent there is currently no correct portable way to use it for caching
  551. macro expansions.
  552.  
  553.    *  Caching by displacement (performing a side effect on the macro-call form)
  554.      won't work because the same (eq) macro-call form may appear in distinct
  555.      lexical contexts. In addition, the macro-call form may be a read-only
  556.      constant (see quote and also section 25.1).
  557.  
  558.    *  Caching by table lookup won't work because such a table would have to be
  559.      keyed by both the macro-call form and the environment, but X3J13 voted in
  560.      March 1989 (MACRO-ENVIRONMENT-EXTENT)   to permit macro environments to
  561.      have only dynamic extent.
  562.  
  563.    *  Caching by storing macro-call forms and expansions within the environment
  564.      object itself would work, but there are no portable primitives that would
  565.      allow users to do this.
  566.  
  567. X3J13 also noted that, although there seems to be no correct portable way to
  568. use *macroexpand-hook* to cache macro expansions, there is no requirement that
  569. an implementation call the macro expansion function more than once for a given
  570. form and lexical environment.
  571.  
  572. X3J13 voted in March 1989 (SYMBOL-MACROLET-SEMANTICS)   to specify that
  573. macroexpand-1 will also expand symbol macros defined by symbol-macrolet;
  574. therefore a form may also be a macro call if it is a symbol. The vote did not
  575. address the interaction of this feature with the *macroexpand-hook* function.
  576. An obvious implementation choice is that the hook function is indeed called and
  577. given a special expansion function that, when applied to the form (a symbol)
  578. and env, will produce the expansion, just as for an ordinary macro; but this is
  579. only my suggestion.
  580. [change_end]
  581.  
  582. The evaluator expands macro calls as if through the use of macroexpand-1; the
  583. point is that eval also uses *macroexpand-hook*.
  584.  
  585. macroexpand is similar to macroexpand-1, but repeatedly expands form until it
  586. is no longer a macro call. (In effect, macroexpand simply calls macroexpand-1
  587. repeatedly until the second value returned is nil.) A second value of t or nil
  588. is returned as for macroexpand-1, indicating whether the original form was a
  589. macro call.
  590.  
  591. [Variable]
  592. *macroexpand-hook*
  593.  
  594. The value of *macroexpand-hook* is used as the expansion interface hook by
  595. macroexpand-1.
  596.  
  597. -------------------------------------------------------------------------------
  598.  
  599. 8.3. Destructuring
  600.  
  601. [change_begin]
  602. X3J13 voted in March 1989 (DESTRUCTURING-BIND)   to make the destructuring
  603. feature of defmacro available as a separate facility.
  604.  
  605. [Macro]
  606.  
  607. destructuring-bind lambda-list expression {declaration}* {form}*
  608.  
  609. This macro binds the variables specified in lambda-list to the corresponding
  610. values in the tree structure resulting from evaluating the expression, then
  611. executes the forms as an implicit progn.
  612.  
  613. A destructuring-bind lambda-list may contain the lambda-list keywords
  614. &optional, &rest, &key, &allow-other-keys, and &aux; &body and &whole may also
  615. be used as they are in defmacro, but &environment may not be used. Nested and
  616. dotted lambda-lists are also permitted as for defmacro. The idea is that a
  617. destructuring-bind lambda-list has the same format as inner levels of a
  618. defmacro lambda-list.
  619.  
  620. If the result of evaluating the expression does not match the destructuring
  621. pattern, an error should be signaled.
  622. [change_end]
  623.  
  624. -------------------------------------------------------------------------------
  625.  
  626. 8.4. Compiler Macros
  627.  
  628. [change_begin]
  629. X3J13 voted in June 1989 (DEFINE-COMPILER-MACRO)   to add a facility for
  630. defining compiler macros that take effect only when compiling code, not when
  631. interpreting it.
  632.  
  633. The purpose of this facility is to permit selective source-code transformations
  634. only when the compiler is processing the code. When the compiler is about to
  635. compile a non-atomic form, it first calls compiler-macroexpand-1 repeatedly
  636. until there is no more expansion (there might not be any to begin with). Then
  637. it continues its remaining processing, which may include calling macroexpand-1
  638. and so on.
  639.  
  640. The compiler is required to expand compiler macros. It is unspecified whether
  641. the interpreter does so. The intention is that only the compiler will do so,
  642. but the range of possible ``compiled-only'' implementation strategies precludes
  643. any firm specification.
  644.  
  645. [Macro]
  646.  
  647. define-compiler-macro name lambda-list {declaration | doc-string}* {form}*
  648.  
  649. This is just like defmacro except the definition is not stored in the symbol
  650. function cell of name and is not seen by macroexpand-1. It is, however, seen by
  651. compiler-macroexpand-1. As with defmacro, the lambda-list may include
  652. &environment and &whole and may include destructuring. The definition is
  653. global. (There is no provision for defining local compiler macros in the way
  654. that macrolet defines local macros.)
  655.  
  656. A top-level call to define-compiler-macro in a file being compiled by
  657. compile-file has an effect on the compilation environment similar to that of a
  658. call to defmacro, except it is noticed as a compiler macro (see section 25.1).
  659.  
  660. Note that compiler macro definitions do not appear in information returned by
  661. function-information; they are global, and their interaction with other lexical
  662. and global definitions can be reconstructed by compiler-macro-function. It is
  663. up to code-walking programs to decide whether to invoke compiler macro
  664. expansion.
  665.  
  666. X3J13 voted in March 1988 (FLET-IMPLICIT-BLOCK)   to specify that the body of
  667. the expander function defined by defmacro is implicitly enclosed in a block
  668. construct whose name is the same as the name of the defined macro; presumably
  669. this applies also to define-compiler-macro. Therefore return-from may be used
  670. to exit from the function.
  671.  
  672. [Function]
  673. compiler-macro-function name &optional env
  674.  
  675. The name must be a symbol. If it has been defined as a compiler macro, then
  676. compiler-macro-function returns the macro expansion function; otherwise it
  677. returns nil. The lexical environment env may override any global definition for
  678. name by defining a local function or local macro (such as by flet, labels, or
  679. macrolet) in which case nil is returned.
  680.  
  681. setf may be used with compiler-macro-function to install a function as the
  682. expansion function for the compiler macro name, in the same manner as for
  683. macro-function. Storing the value nil removes any existing compiler macro
  684. definition. As with macro-function, a non-nil stored value must be a function
  685. of two arguments, the entire macro call and the environment. The second
  686. argument to compiler-macro-function must be omitted when it is used with setf.
  687.  
  688. [Function]
  689. compiler-macroexpand form &optional env
  690. compiler-macroexpand-1 form &optional env
  691.  
  692. These are just like macroexpand and macroexpand-1 except that the expander
  693. function is obtained as if by a call to compiler-macro-function on the car of
  694. the form rather than by a call to macro-function. Note that
  695. compiler-macroexpand performs repeated expansion but compiler-macroexpand-1
  696. performs at most one expansion. Two values are returned, the expansion (or the
  697. original form) and a value that is true if any expansion occurred and nil
  698. otherwise.
  699.  
  700. There are three cases where no expansion happens:
  701.  
  702.    *  There is no compiler macro definition for the car of form.
  703.    *  There is such a definition but there is also a notinline declaration,
  704.      either globally or in the lexical environment env.
  705.    *  A global compiler macro definition is shadowed by a local function or
  706.      macro definition (such as by flet, labels, or macrolet).
  707.  
  708. Note that if there is no expansion, the original form is returned as the first
  709. value, and nil as the second value.
  710.  
  711. Any macro expansion performed by the function compiler-macroexpand or by the
  712. function compiler-macroexpand-1 is carried out by calling the function that is
  713. the value of *macroexpand-hook*.
  714.  
  715. A compiler macro may decline to provide any expansion merely by returning the
  716. original form. This is useful when using the facility to put ``compiler
  717. optimizers'' on various function names. For example, here is a compiler macro
  718. that ``optimizes'' (one would hope) the zero-argument and one-argument cases of
  719. a function called plus:
  720.  
  721. (define-compiler-macro plus (&whole form &rest args)
  722.   (case (length args)
  723.     (0 0)
  724.     (1 (car args))
  725.     (t form)))
  726.  
  727. [change_end]
  728.  
  729. -------------------------------------------------------------------------------
  730.  
  731. 8.5. Environments
  732.  
  733. [change_begin]
  734. X3J13 voted in June 1989 (SYNTACTIC-ENVIRONMENT-ACCESS)   to add some
  735. facilities for obtaining information from environment objects of the kind
  736. received as arguments by macro expansion functions, *macroexpand-hook*
  737. functions, and *evalhook* functions. There is a minimal set of accessors
  738. (variable-information, function-information, and declaration-information) and a
  739. constructor (augment-environment) for environments.
  740.  
  741. All of the standard declaration specifiers, with the exception of special, can
  742. be defined fairly easily using define-declaration. It also seems to be able to
  743. handle most extended declarations.
  744.  
  745. The function parse-macro is provided so that users don't have to write their
  746. own code to destructure macro arguments. This function is not entirely
  747. necessary since X3J13 voted in March 1989 (DESTRUCTURING-BIND)   to add
  748. destructuring-bind to the language. However, parse-macro is worth having
  749. anyway, since any program-analyzing program is going to need to define it, and
  750. the implementation isn't completely trivial even with destructuring-bind to
  751. build upon.
  752.  
  753. The function enclose allows expander functions to be defined in a non-null
  754. lexical environment, as required by the vote of X3J13 in March 1989
  755. (DEFINING-MACROS-NON-TOP-LEVEL)   . It also provides a mechanism by which a
  756. program processing the body of an (eval-when (:compile-toplevel) ...) form can
  757. execute it in the enclosing environment (see issue (EVAL-WHEN-NON-TOP-LEVEL)
  758. ).
  759.  
  760. In all of these functions the argument named env is an environment object. (It
  761. is not required that implementations provide a distinguished representation for
  762. such objects.) Optional env arguments default to nil, which represents the
  763. local null lexical environment (containing only global definitions and
  764. proclamations that are present in the run-time environment). All of these
  765. functions should signal an error of type type-error if the value of an
  766. environment argument is not a syntactic environment object.
  767.  
  768. The accessor functions variable-information, function-information, and
  769. declaration-information retrieve information about declarations that are in
  770. effect in the environment. Since implementations are permitted to ignore
  771. declarations (except for special declarations and optimize safety declarations
  772. if they ever compile unsafe code), these accessors are required only to return
  773. information about declarations that were explicitly added to the environment
  774. using augment-environment. They might also return information about
  775. declarations recognized and added to the environment by the interpreter or the
  776. compiler, but that is at the discretion of the implementor. Implementations are
  777. also permitted to canonicalize declarations, so the information returned by the
  778. accessors might not be identical to the information that was passed to
  779. augment-environment.
  780.  
  781. [Function]
  782. variable-information variable &optional env
  783.  
  784. This function returns information about the interpretation of the symbol
  785. variable when it appears as a variable within the lexical environment env.
  786. Three values are returned.
  787.  
  788. The first value indicates the type of definition or binding for variable in
  789. env:
  790.  
  791. nil  There is no apparent definition or binding for variable.
  792.  
  793. :special
  794.      The variable refers to a special variable, either declared or proclaimed.
  795.  
  796. :lexical
  797.      The variable refers to a lexical variable.
  798.  
  799. :symbol-macro
  800.      The variable refers to a symbol-macrolet binding.
  801.  
  802. :constant
  803.      Either the variable refers to a named constant defined by defconstant or
  804.      the variable is a keyword symbol.
  805.  
  806. The second value indicates whether there is a local binding of the name. If the
  807. name is locally bound, the second value is true; otherwise, the second value is
  808. nil.
  809.  
  810. The third value is an a-list containing information about declarations that
  811. apply to the apparent binding of the variable. The keys in the a-list are
  812. symbols that name declaration specifiers, and the format of the corresponding
  813. value in the cdr of each pair depends on the particular declaration name
  814. involved. The standard declaration names that might appear as keys in this
  815. a-list are:
  816.  
  817. dynamic-extent
  818.      A non-nil value indicates that the variable has been declared
  819.      dynamic-extent. If the value is nil, the pair might be omitted.
  820.  
  821. ignore
  822.      A non-nil value indicates that the variable has been declared ignore. If
  823.      the value is nil, the pair might be omitted.
  824.  
  825. type
  826.      The value is a type specifier associated with the variable by a type
  827.      declaration or an abbreviated declaration such as (fixnum variable). If no
  828.      explicit association exists, either by proclaim or declare, then the type
  829.      specifier is t. It is permissible for implementations to use a type
  830.      specifier that is equivalent to or a supertype of the one appearing in the
  831.      original declaration. If the value is t, the pair might be omitted.
  832.  
  833. If an implementation supports additional declaration specifiers that apply to
  834. variable bindings, those declaration names might also appear in the a-list.
  835. However, the corresponding key must not be a symbol that is external in any
  836. package defined in the standard or that is otherwise accessible in the
  837. common-lisp-user package.
  838.  
  839. The a-list might contain multiple entries for a given key. The consequences of
  840. destructively modifying the list structure of this a-list or its elements
  841. (except for values that appear in the a-list as a result of define-declaration)
  842. are undefined.
  843.  
  844. Note that the global binding might differ from the local one and can be
  845. retrieved by calling variable-information with a null lexical environment.
  846.  
  847. [Function]
  848. function-information function &optional env
  849.  
  850. This function returns information about the interpretation of the function-name
  851. function when it appears in a functional position within lexical environment
  852. env. Three values are returned.
  853.  
  854. The first value indicates the type of definition or binding of the
  855. function-name which is apparent in env:
  856.  
  857. nil  There is no apparent definition for function.
  858.  
  859. :function
  860.      The function refers to a function.
  861.  
  862. :macro
  863.      The function refers to a macro.
  864.  
  865. :special-form
  866.      The function refers to a special form.
  867.  
  868. Some function-names can refer to both a global macro and a global special form.
  869. In such a case the macro takes precedence and :macro is returned as the first
  870. value.
  871.  
  872. The second value specifies whether the definition is local or global. If local,
  873. the second value is true; it is nil when the definition is global.
  874.  
  875. The third value is an a-list containing information about declarations that
  876. apply to the apparent binding of the function. The keys in the a-list are
  877. symbols that name declaration specifiers, and the format of the corresponding
  878. values in the cdr of each pair depends on the particular declaration name
  879. involved. The standard declaration names that might appear as keys in this
  880. a-list are:
  881.  
  882. dynamic-extent
  883.      A non-nil value indicates that the function has been declared
  884.      dynamic-extent. If the value is nil, the pair might be omitted.
  885.  
  886. inline
  887.      The value is one of the symbols inline, notinline, or nil to indicate
  888.      whether the function-name has been declared inline, declared notinline, or
  889.      neither, respectively. If the value is nil, the pair might be omitted.
  890.  
  891. ftype
  892.      The value is the type specifier associated with the function-name in the
  893.      environment, or the symbol function if there is no functional type
  894.      declaration or proclamation associated with the function-name. This value
  895.      might not include all the apparent ftype declarations for the
  896.      function-name. It is permissible for implementations to use a type
  897.      specifier that is equivalent to or a supertype of the one that appeared in
  898.      the original declaration. If the value is function, the pair might be
  899.      omitted.
  900.  
  901. If an implementation supports additional declaration specifiers that apply to
  902. function bindings, those declaration names might also appear in the a-list.
  903. However, the corresponding key must not be a symbol that is external in any
  904. package defined in the standard or that is otherwise accessible in the
  905. common-lisp-user package.
  906.  
  907. The a-list might contain multiple entries for a given key. In this case the
  908. value associated with the first entry has precedence. The consequences of
  909. destructively modifying the list structure of this a-list or its elements
  910. (except for values that appear in the a-list as a result of define-declaration)
  911. are undefined.
  912.  
  913. Note that the global binding might differ from the local one and can be
  914. retrieved by calling function-information with a null lexical environment.
  915.  
  916. [Function]
  917. declaration-information decl-name &optional env
  918.  
  919. This function returns information about declarations named by the symbol
  920. decl-name that are in force in the environment env. Only declarations that do
  921. not apply to function or variable bindings can be accessed with this function.
  922. The format of the information that is returned depends on the decl-name
  923. involved.
  924.  
  925. It is required that this function recognize optimize and declaration as
  926. decl-names. The values returned for these two cases are as follows:
  927.  
  928. optimize
  929.      A single value is returned, a list whose entries are of the form (quality
  930.      value), where quality is one of the standard optimization qualities
  931.      (speed, safety, compilation-speed, space, debug) or some
  932.      implementation-specific optimization quality, and value is an integer in
  933.      the range 0 to 3 (inclusive). The returned list always contains an entry
  934.      for each of the standard qualities and for each of the
  935.      implementation-specific qualities. In the absence of any previous
  936.      declarations, the associated values are implementation-dependent. The list
  937.      might contain multiple entries for a quality, in which case the first such
  938.      entry specifies the current value. The consequences of destructively
  939.      modifying this list or its elements are undefined.
  940.  
  941. declaration
  942.      A single value is returned, a list of the declaration names that have been
  943.      proclaimed as valid through the use of the declaration proclamation. The
  944.      consequences of destructively modifying this list or its elements are
  945.      undefined.
  946.  
  947. If an implementation is extended to recognize additional declaration specifiers
  948. in declare or proclaim, it is required that either the declaration-information
  949. function should recognize those declarations also or the implementation should
  950. provide a similar accessor that is specialized for that declaration specifier.
  951. If declaration-information is used to return the information, the corresponding
  952. decl-name must not be a symbol that is external in any package defined in the
  953. standard or that is otherwise accessible in the common-lisp-user package.
  954.  
  955. [Function]
  956.  
  957. augment-environment env &key :variable :symbol-macro
  958.                     :function :macro :declare
  959.  
  960. This function returns a new environment containing the information present in
  961. env augmented with the information provided by the keyword arguments. It is
  962. intended to be used by program analyzers that perform a code walk.
  963.  
  964. The arguments are supplied as follows.
  965.  
  966. :variable
  967.      The argument is a list of symbols that will be visible as bound variables
  968.      in the new environment. Whether each binding is to be interpreted as
  969.      special or lexical depends on special declarations recorded in the
  970.      environment or provided in the :declare argument.
  971.  
  972. :symbol-macro
  973.      The argument is a list of symbol macro definitions, each of the form (name
  974.      definition); that is, the argument is in the same format as the cadr of a
  975.      symbol-macrolet special form. The new environment will have local
  976.      symbol-macro bindings of each symbol to the corresponding expansion, so
  977.      that macroexpand will be able to expand them properly. A type declaration
  978.      in the :declare argument that refers to a name in this list implicitly
  979.      modifies the definition associated with the name. The effect is to wrap a
  980.      the form mentioning the type around the definition.
  981.  
  982. :function
  983.      The argument is a list of function-names that will be visible as local
  984.      function bindings in the new environment.
  985.  
  986. :macro
  987.      The argument is a list of local macro definitions, each of the form (name
  988.      definition). Note that the argument is not in the same format as the cadr
  989.      of a macrolet special form. Each definition must be a function of two
  990.      arguments (a form and an environment). The new environment will have local
  991.      macro bindings of each name to the corresponding expander function, which
  992.      will be returned by macro-function and used by macroexpand.
  993.  
  994. :declare
  995.      The argument is a list of declaration specifiers. Information about these
  996.      declarations can be retrieved from the resulting environment using
  997.      variable-information, function-information, and declaration-information.
  998.  
  999. The consequences of subsequently destructively modifying the list structure of
  1000. any of the arguments to this function are undefined.
  1001.  
  1002. An error is signaled if any of the symbols naming a symbol macro in the
  1003. :symbol-macro argument is also included in the :variable argument. An error is
  1004. signaled if any symbol naming a symbol macro in the :symbol-macro argument is
  1005. also included in a special declaration specifier in the :declare argument. An
  1006. error is signaled if any symbol naming a macro in the :macro argument is also
  1007. included in the :function argument. The condition type of each of these errors
  1008. is program-error.
  1009.  
  1010. The extent of the returned environment is the same as the extent of the
  1011. argument environment env. The result might share structure with env but env is
  1012. not modified.
  1013.  
  1014. While an environment argument received by an *evalhook* function is permitted
  1015. to be used as the environment argument to augment-environment, the consequences
  1016. are undefined if an attempt is made to use the result of augment-environment as
  1017. the environment argument for evalhook. The environment returned by
  1018. augment-environment can be used only for syntactic analysis, that is, as an
  1019. argument to the functions defined in this section and functions such as
  1020. macroexpand.
  1021.  
  1022. [Macro]
  1023. define-declaration decl-name lambda-list {form}*
  1024.  
  1025. This macro defines a handler for the named declaration. It is the mechanism by
  1026. which augment-environment is extended to support additional declaration
  1027. specifiers. The function defined by this macro will be called with two
  1028. arguments, a declaration specifier whose car is decl-name and the env argument
  1029. to augment-environment. This function must return two values. The first value
  1030. must be one of the following keywords:
  1031.  
  1032. :variable
  1033.      The declaration applies to variable bindings.
  1034. :function
  1035.      The declaration applies to function bindings.
  1036. :declare
  1037.      The declaration does not apply to bindings.
  1038.  
  1039. If the first value is :variable or :function then the second value must be a
  1040. list, the elements of which are lists of the form (binding-name key value). If
  1041. the corresponding information function (either variable-information or
  1042. function-information) is applied to the binding-name and the augmented
  1043. environment, the a-list returned by the information function as its third value
  1044. will contain the value under the specified key.
  1045.  
  1046. If the first value is :declare, the second value must be a cons of the form
  1047. (key . value). The function declaration-information will return value when
  1048. applied to the key and the augmented environment.
  1049.  
  1050. define-declaration causes decl-name to be proclaimed to be a declaration; it is
  1051. as if its expansion included a call (proclaim '(declaration decl-name)). As is
  1052. the case with standard declaration specifiers, the evaluator and compiler are
  1053. permitted, but not required, to add information about declaration specifiers
  1054. defined with define-declaration to the macro expansion and *evalhook*
  1055. environments.
  1056.  
  1057. The consequences are undefined if decl-name is a symbol that can appear as the
  1058. car of any standard declaration specifier.
  1059.  
  1060. The consequences are also undefined if the return value from a declaration
  1061. handler defined with define-declaration includes a key name that is used by the
  1062. corresponding accessor to return information about any standard declaration
  1063. specifier. (For example, if the first return value from the handler is
  1064. :variable, the second return value may not use the symbols dynamic-extent,
  1065. ignore, or type as key names.)
  1066.  
  1067. The define-declaration macro does not have any special compile-time side
  1068. effects (see section 25.1).
  1069.  
  1070. [Function]
  1071. parse-macro name lambda-list body &optional env
  1072.  
  1073. This function is used to process a macro definition in the same way as defmacro
  1074. and macrolet. It returns a lambda-expression that accepts two arguments, a form
  1075. and an environment. The name, lambda-list, and body arguments correspond to the
  1076. parts of a defmacro or macrolet definition.
  1077.  
  1078. The lambda-list argument may include &environment and &whole and may include
  1079. destructuring. The name argument is used to enclose the body in an implicit
  1080. block and might also be used for implementation-dependent purposes (such as
  1081. including the name of the macro in error messages if the form does not match
  1082. the lambda-list).
  1083.  
  1084. [Function]
  1085. enclose lambda-expression &optional env
  1086.  
  1087. This function returns an object of type function that is equivalent to what
  1088. would be obtained by evaluating `(function ,lambda-expression) in a syntactic
  1089. environment env. The lambda-expression is permitted to reference only the parts
  1090. of the environment argument env that are relevant only to syntactic processing,
  1091. specifically declarations and the definitions of macros and symbol macros. The
  1092. consequences are undefined if the lambda-expression contains any references to
  1093. variable or function bindings that are lexically visible in env, any go to a
  1094. tag that is lexically visible in env, or any return-from mentioning a block
  1095. name that is lexically visible in env.
  1096.  
  1097. [change_end]
  1098.  
  1099. -------------------------------------------------------------------------------
  1100.  
  1101.  
  1102.  
  1103.